package com.samsung.actividades;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.samsung.actividades.Logs;
import com.samsung.R;
import com.samsung.database.Orden;
import com.samsung.database.PartesDBAdapter;
import com.samsung.seleccion.MyWebView;



public class Inicio extends Activity implements OnItemSelectedListener,
		OnCheckedChangeListener {

	private AutoCompleteTextView autoModelo;
	private Inicio instanceInicio;
	protected String _pathestado;
	protected String _pathsintoma;
	
	/*protected String _pathestado_new;
	protected String _pathsitnoma_new;*/
	
	
	// Base de datos
	PartesDBAdapter partesDBAdapter;
	private Cursor partesCursor;

	// protected Button _button;
	protected ImageView _imageestado;
	protected ImageView _imagesintoma;
	protected TextView _field;
	protected boolean _takenestado;
	protected boolean _takensintoma;
	private ArrayList<String> modelos;
	private ArrayAdapter<String> aaModelos;

	protected static final String PHOTO_TAKEN_ESTADO = "photo_taken_estado";
	protected static final String PHOTO_TAKEN_SINTOMA = "photo_taken_sintoma";
	
	protected static final String PATH_SINTOMA = "_pathestado";
	protected static final String PATH_ESTADO = "_pathsintoma";
	
	protected static final String PATH_IDENT = "ident";
	
	Orden orden;
	private Bundle bundle;
	private Spinner sintomaSpinner;
	private Spinner estadoSpinner;
	private TextView numero;
	public static String KEY_ORDEN = "ORDEN";

	private static final String KEY_PARTES_SIZE = "PARTES_SIZE";
	public int total_partes;
	private final String KEY_NUMERO = "NUMERO";
	private final String KEY_ESTADO = "ESTADO";
	private final String KEY_SINTOMA = "SINTOMA";
	private final String KEY_MODELO = "MODELO";

	private final String KEY_NROPARTE = "nro_parte";
	private final String KEY_CODIGO = "codigo";
	private final String KEY_NOMBRE_DESC = "nombre_desc";

	private CheckBox cbObservaciones;
	private EditText edOtroEstado;
	private TextView tvContinuar;

	private CheckBox cbObservaciones2;
	private EditText edOtroSintoma;
	private EditText edBarras;
	private TextView tvContinuar2;

	
	private String numero1;
	private String numero2;
	private String numero3;
	
	private Logs log=new Logs();
	
	
	String ident="";

	String ruta;	
	String ruta_parte="";
	
	File file;
	File temp_file;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		
	super.onCreate(savedInstanceState);
	
	
	partesDBAdapter = new PartesDBAdapter(this);
	partesDBAdapter.open();	
	
	partesCursor = partesDBAdapter.getRuta();
	startManagingCursor(partesCursor);	
	
	if(partesCursor.moveToFirst()){
		ruta_parte = partesCursor.getString(partesCursor.getColumnIndex(PartesDBAdapter.KEY_VALOR));					
	}
	
	orden = new Orden();
		setContentView(R.layout.inicio);
		// Dave - Inicio - 0
		// Se setea las posiciones - Estado
		cbObservaciones = (CheckBox) findViewById(R.id.chckNoContinuar);
		cbObservaciones.setOnCheckedChangeListener(this);
		edOtroEstado = (EditText) findViewById(R.id.otroEstado);
		if (savedInstanceState != null) {
			try {
				String estado = savedInstanceState.getString("estado");
				edOtroEstado.setText(estado);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}		
		
		tvContinuar = (TextView) findViewById(R.id.LabelContinuar);
		// Se setea las posiciones - Sintoma
		cbObservaciones2 = (CheckBox) findViewById(R.id.chckNoContinuar2);
		cbObservaciones2.setOnCheckedChangeListener(this);
		edOtroSintoma = (EditText) findViewById(R.id.otroSintoma);
		if (savedInstanceState != null) {
			try {
				String sintoma = savedInstanceState.getString("sintoma");
				edOtroSintoma.setText(sintoma);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		tvContinuar2 = (TextView) findViewById(R.id.LabelContinuar2);
		// Dave - Fin - 0
		
		// SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy hh:mm");
		// String dateString = sdf.format(d);
		
		if (savedInstanceState != null) {
			try {
				_pathestado  = savedInstanceState.getString("_pathestado");	
				ident  = savedInstanceState.getString("ident");	
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		else{ ident=log.gethora();
		_pathestado = Environment.getExternalStorageDirectory() + ruta_parte + "IMGEST"+ident+".jpg";
		}
		
		
		
		if (savedInstanceState != null) {
			try {
				_pathsintoma  = savedInstanceState.getString("_pathsintoma");				
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		else{ 
		ident=log.gethora();
		_pathsintoma = Environment.getExternalStorageDirectory() + ruta_parte + "IMGSIN"+ident+".jpg";
	    }

		instanceInicio = this;

		numero = (TextView) findViewById(R.id.editText1);
		if (savedInstanceState != null) {
			try {
				String numeros = savedInstanceState.getString("numero");
				numero.setText(numeros);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		estadoSpinner = (Spinner) findViewById(R.id.estado);
		// Dave - Inicio - 1
		estadoSpinner.setOnItemSelectedListener(this);
		// Dave - Fin - 1

		ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
				R.array.ESTADO, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		estadoSpinner.setAdapter(adapter);
		if (savedInstanceState != null) {
			try {
				int estadosp = savedInstanceState.getInt("estadosp");
				estadoSpinner.setSelection(estadosp);		
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		sintomaSpinner = (Spinner) findViewById(R.id.sintoma);

		
		// Dave - Inicio - 2
		sintomaSpinner.setOnItemSelectedListener(this);
		// Dave - Fin - 2
		ArrayAdapter adapter2 = ArrayAdapter.createFromResource(this,
				R.array.SINTOMA, android.R.layout.simple_spinner_item);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sintomaSpinner.setAdapter(adapter2);
		if (savedInstanceState != null) {
			try {
				int sintomasp = savedInstanceState.getInt("sintomasp");
				sintomaSpinner.setSelection(sintomasp );		
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		Button sgte = (Button) findViewById(R.id.siguiente);
		sgte.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				
//				if(partesCursor.moveToFirst()){
//					ruta= partesCursor.getString(partesCursor.getColumnIndex(PartesDBAdapter.KEY_VALOR));
//					if(ruta.equals("")) ruta= "/sdcard/";					
//				}
//				else ruta= "/sdcard/";				
				
				
				ruta= Environment.getExternalStorageDirectory() + ruta_parte;
				
				
				partesDBAdapter.close();
				Intent i = new Intent(instanceInicio, MyWebView.class);
				fillOrden();
				
				
				
//				file = new File(_pathestado);				
//				
//				_pathestado_new = Environment.getExternalStorageDirectory() + ruta_parte + "IMGEST"
//				+ log.getfecha() +orden.getNumero()+".jpg";
//				
//				temp_file = new File(_pathestado_new);	
//				
//				file.renameTo(temp_file);
//				
//				file = new File(_pathsintoma);				
//				
//				_pathsitnoma_new = Environment.getExternalStorageDirectory() + ruta_parte + "IMGSIN"
//				+ log.getfecha() +orden.getNumero()+".jpg";
//
//				temp_file = new File(_pathsitnoma_new);	
//				
//				file.renameTo(temp_file);
				
				log.setLog(ruta, orden.getNumero(), "Visita",
						orden.getEstado(), orden.getSintoma(),
						orden.getModelo(), _pathestado, _pathsintoma);
				
				i.putExtra(KEY_ORDEN, orden);
				startActivity(i);
			}
		});

		// Create the array list of to do items
		modelos = (ArrayList<String>) getLastNonConfigurationInstance();
		if (modelos == null)
			modelos = new ArrayList<String>();

		// readTasks();
		aaModelos = new ArrayAdapter<String>(this,
		// android.R.layout.simple_list_item_1, todoItems);
				R.layout.list_item, modelos);

		/*
		 * String[] modelos = getResources().getStringArray(R.array.MODELOS);
		 * ArrayAdapter<String> a = new ArrayAdapter<String>(this,
		 * android.R.layout.simple_list_item_1, modelos);
		 */

		autoModelo = (AutoCompleteTextView) findViewById(R.id.codModelo);
		if (savedInstanceState != null) {
			try {
				String modelo = savedInstanceState.getString("modelo");
				autoModelo.setText(modelo); 
				
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		// autoModelo.addTextChangedListener(this);
		autoModelo.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, modelos));
		
		edBarras = (EditText) findViewById(R.id.Edbarras);
		
		Resources res = getResources();

		Button camEstado = (Button) findViewById(R.id.camEstado);

		camEstado.setBackgroundDrawable(res.getDrawable(R.drawable.camera));
		camEstado.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Log.i("MakeMachine", "ButtonClickHandler.onClick()");
				startCameraActivityEstado();
			}
		});

		Button camSintoma = (Button) findViewById(R.id.camSintoma);
		camSintoma.setBackgroundDrawable(res.getDrawable(R.drawable.camera));

		camSintoma.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Log.i("MakeMachine", "ButtonClickHandler.onClick()");
				startCameraActivitySintoma();
			}
		});
		
		Button camBarras = (Button) findViewById(R.id.camBarras);
		camBarras.setBackgroundDrawable(res.getDrawable(R.drawable.barcode));
		camBarras.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intent2 = new Intent(
						"com.google.zxing.client.android.SCAN");
				intent2.setPackage("com.google.zxing.client.android");				
				startActivityForResult(intent2, 2);
			}
		});

		_imageestado = (ImageView) findViewById(R.id.camEstadoImg);
		_imagesintoma = (ImageView) findViewById(R.id.camSintomaImg);

		_field = (TextView) findViewById(R.id.otroEstado);
		_field.setVisibility(View.INVISIBLE);

		partesDBAdapter = new PartesDBAdapter(this);
		partesDBAdapter.open();
		cargarDatos();

	}

	protected void fillOrden() {
		String value = numero.getText().toString();
		orden.setNumero(value);
		value = estadoSpinner.getSelectedItem().toString();
		orden.setEstado(value);
		value = sintomaSpinner.getSelectedItem().toString();
		orden.setSintoma(value);
		value = autoModelo.getText().toString();
		orden.setModelo(value);
	}

	private void cargarDatos() {
		// Obtener todos los items desde la base de datos
		partesCursor = partesDBAdapter.getModelosCursor();
		startManagingCursor(partesCursor);
		updateArray();
	}

	private void updateArray() {

		partesCursor.requery();
		modelos.clear();

		if (partesCursor.moveToFirst()) {

			do {
				int index = partesCursor
						.getColumnIndex(PartesDBAdapter.KEY_MODELO);
				String modelo = partesCursor.getString(index);
				modelos.add(modelo);
				// System.out.println("modelo "+modelo);
			} while (partesCursor.moveToNext());
			// partesCursor.moveToNext();
			// } while (modelos.size() != 10);

			aaModelos.notifyDataSetChanged();
		}
	}

	protected void startCameraActivityEstado() {
		Log.i("MakeMachine", "startCameraActivity()");
		File file = new File(_pathestado);
		Uri outputFileUri = Uri.fromFile(file);
		Intent intent = new Intent(
				android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		startActivityForResult(intent, 1);

	}
	
	protected void startCameraActivitySintoma() {
		Log.i("MakeMachine", "startCameraActivity()");
		File file = new File(_pathsintoma);
		Uri outputFileUri = Uri.fromFile(file);
		Intent intent = new Intent(
				android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		startActivityForResult(intent, 3);

	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 2) {
			if (resultCode == RESULT_OK) {
				String contents = data.getStringExtra("SCAN_RESULT");
				String format = data.getStringExtra("SCAN_RESULT_FORMAT");
				edBarras.setText(contents);

			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, R.string.scan_canceled, Toast.LENGTH_SHORT)
						.show();
			}
		} else if (requestCode == 1) {

			Log.i("MakeMachine", "resultCode: " + resultCode);
			switch (resultCode) {
			case 0:
				Log.i("MakeMachine", "User cancelled");
				break;

			case -1:
				onPhotoTakenEstado();
				break;
			}
		} else if (requestCode == 3) {

			Log.i("MakeMachine", "resultCode: " + resultCode);
			switch (resultCode) {
			case 0:
				Log.i("MakeMachine", "User cancelled");
				break;

			case -1:
				onPhotoTakenSintoma();
				break;
			}
		}
	}

	protected void onPhotoTakenEstado() {
		Log.i("MakeMachine", "onPhotoTaken");
		_takenestado = true;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 4;
		Bitmap bitmap = BitmapFactory.decodeFile(_pathestado, options);
		_imageestado.setImageBitmap(bitmap);
		_field.setText(_pathestado);
		_field.setVisibility(View.GONE);

	}
	
	protected void onPhotoTakenSintoma() {
		Log.i("MakeMachine", "onPhotoTaken");
		_takensintoma = true;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 4;
		Bitmap bitmap = BitmapFactory.decodeFile(_pathsintoma, options);
		_imagesintoma.setImageBitmap(bitmap);
		_field.setText(_pathsintoma);
		_field.setVisibility(View.GONE);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		Log.i("MakeMachine", "onRestoreInstanceState()");
		if (savedInstanceState.getBoolean(Inicio.PHOTO_TAKEN_ESTADO)) {
			onPhotoTakenEstado();
		}
		if (savedInstanceState.getBoolean(Inicio.PHOTO_TAKEN_SINTOMA)) {
			onPhotoTakenSintoma();
		}
		_pathestado=savedInstanceState.getString(Inicio.PATH_ESTADO);
		_pathsintoma=savedInstanceState.getString(Inicio.PATH_SINTOMA);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putBoolean(Inicio.PHOTO_TAKEN_ESTADO, _takenestado);
		outState.putBoolean(Inicio.PHOTO_TAKEN_SINTOMA, _takensintoma);
		
		try {
			String numeros = numero.getText().toString();
			outState.putString("numero", numeros);
		} catch (Exception e) {
			// TODO: handle exception
		}		
		
		try {
			String estados = edOtroEstado.getText().toString();
			outState.putString("estado", estados);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
			String sintomas = edOtroSintoma.getText().toString();
			outState.putString("sintoma", sintomas);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
			String modelos = autoModelo.getText().toString();
			outState.putString("modelo", modelos );
		} catch (Exception e) {
			// TODO: handle exception
		}

		try {
			int sintomasp = sintomaSpinner.getSelectedItemPosition();
			outState.putInt("sintomasp", sintomasp );
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
			int estadosp = estadoSpinner.getSelectedItemPosition();
			outState.putInt("estadosp", estadosp );
		} catch (Exception e) {
			// TODO: handle exception
		}	
		
		//outState.putString(Inicio.PATH_ESTADO, _pathestado);
		//outState.putString(Inicio.PATH_SINTOMA, _pathsintoma);
		
		try {
			outState.putString("_pathestado", _pathestado );
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
			outState.putString("_pathsintoma", _pathsintoma );
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
			String modelos = autoModelo.getText().toString();
			outState.putString("modelo", modelos );
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		return (modelos);
	}

	// Dave - Inicio - 3
	@Override
	public void onItemSelected(AdapterView<?> arg0, View target, int position,
			long id) {
		// TODO Auto-generated method stub
		String value = estadoSpinner.getSelectedItem().toString();
		String value2 = sintomaSpinner.getSelectedItem().toString();
		if (value.equals("Otros")) {
			cbObservaciones.setClickable(true);
			cbObservaciones.setVisibility(View.VISIBLE);
			tvContinuar.setVisibility(View.VISIBLE);
			chkNoContinuarAction(true);

		} else {
			cbObservaciones.setClickable(false);
			chkNoContinuarAction(false);
		}

		if (value2.equals("Otro Problema")) {
			cbObservaciones2.setClickable(true);
			cbObservaciones2.setVisibility(View.VISIBLE);
			tvContinuar2.setVisibility(View.VISIBLE);
			chkNoContinuarAction2(true);
		} else {
			cbObservaciones2.setClickable(false);
			chkNoContinuarAction2(false);
		}
	}

	public void chkNoContinuarAction(boolean isChecked) {
		if (isChecked) {
			// chckNoContinuar cambiar los botones textEstado

			edOtroEstado.setVisibility(View.VISIBLE);
			edOtroEstado.setHeight(this.convertDipTopixel(300.0f));

			// Modificacion del layout
			RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
			p.addRule(RelativeLayout.BELOW, R.id.otroEstado);
			p.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
			cbObservaciones.setLayoutParams(p);

		} else {
			edOtroEstado.setVisibility(View.GONE);
			edOtroEstado.setHeight(this.convertDipTopixel(10.0f));
			tvContinuar.setVisibility(View.GONE);
			// Modificacion del layout
			RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
			p.addRule(RelativeLayout.BELOW, R.id.estado);
			p.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
			cbObservaciones.setLayoutParams(p);
			cbObservaciones.setVisibility(View.GONE);
		}
	}

	public void chkNoContinuarAction2(boolean isChecked) {
		if (isChecked) {
			// chckNoContinuar cambiar los botones textEstado

			edOtroSintoma.setVisibility(View.VISIBLE);
			edOtroSintoma.setHeight(this.convertDipTopixel(300.0f));

			// Modificacion del layout
			RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
			p.addRule(RelativeLayout.BELOW, R.id.otroSintoma);
			p.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
			cbObservaciones2.setLayoutParams(p);
		} else {
			edOtroSintoma.setVisibility(View.GONE);
			edOtroSintoma.setHeight(this.convertDipTopixel(10.0f));
			tvContinuar2.setVisibility(View.GONE);
			// Modificacion del layout
			RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
			p.addRule(RelativeLayout.BELOW, R.id.sintoma);
			p.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
			cbObservaciones2.setLayoutParams(p);
			cbObservaciones2.setVisibility(View.GONE);
		}
	}

	// Convierte de Pixeles a Dip
	public float convertPixelToDip(int pixel) {
		float dip;
		Resources resources = getResources();
		dip = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 75,
				resources.getDisplayMetrics());
		return dip;
	}

	// Convierte de Dip a Pixeles
	public int convertDipTopixel(float dip) {
		int pixel;
		// Convert the dps to pixels
		final float scale = getResources().getDisplayMetrics().density;
		pixel = (int) (dip * scale + 0.5f);

		// Use mGestureThreshold as a distance in pixels
		return pixel;
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub

	}

}